/*
 * Copyright (c) 2018-2999 广州亚米信息科技有限公司 All rights reserved.
 *
 * https://www.gz-yami.com/
 *
 * 未经允许，不可做商业用途！
 *
 * 版权所有，侵权必究！
 */

package com.yami.shop.service.impl;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.qrcode.QrCodeUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yami.shop.bean.app.dto.UserDto;
import com.yami.shop.bean.dto.InvitationRecord;
import com.yami.shop.bean.dto.UserCardDto;
import com.yami.shop.bean.enums.ProfitTypeConst;
import com.yami.shop.bean.model.User;
import com.yami.shop.bean.model.UserScoreRecord;
import com.yami.shop.bean.param.UserForget;
import com.yami.shop.bean.param.UserRegisterParam;
import com.yami.shop.common.exception.YamiShopBindException;
import com.yami.shop.dao.DistanceMapper;
import com.yami.shop.dao.UserMapper;
import com.yami.shop.service.AttachFileService;
import com.yami.shop.service.CouponRecordService;
import com.yami.shop.service.UserScoreRecordService;
import com.yami.shop.service.UserService;
import ma.glasnost.orika.MapperFacade;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.yaml.snakeyaml.events.Event;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.Random;

/**
 * @author lgh on 2018/09/11.
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    private AttachFileService attachFileService;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private UserScoreRecordService userScoreRecordService;
    @Autowired
    private CouponRecordService couponRecordService;
    @Autowired
    private MapperFacade mapperFacade;
    @Autowired
    private DistanceMapper distanceMapper;

    @Override
    public Boolean insertUser(UserRegisterParam uParam) {

        User mail = getUserByUserMobile(uParam.getUserMobile());
        if (mail != null) {
            throw new YamiShopBindException("账号已存在");
        }
        Date now = new Date();
        User user = new User();
        user.setUserId(IdUtil.simpleUUID());
        user.setModifyTime(now);
        user.setUserRegtime(now);
        user.setSex(uParam.getSex());
        user.setUppInvitatioCode(uParam.getUppInvitatioCode());
        user.setIsFirstVip(0);
        //女性需要审核
        if(user.getSex().equals("M")){
            user.setStatus(1);
            user.setPic(uParam.getPic());
            //男性会送注册礼包
            DateTime reg_gift_endtime = DateUtil.offsetDay(now, 1);
            user.setRegGiftEndtime(reg_gift_endtime);
            user.setRegGiftNum(3);

            String upp = new String();
            upp = user.getUppInvitatioCode();
            if (upp != null){
                //送上级用户邀请礼包
                DateTime inv_gift_endtime = DateUtil.offsetDay(now, 1);
                userMapper.uppCodeRepeat(upp);
            }
        }else{
            user.setStatus(2);
            user.setIdentityPic(uParam.getIdentityPic());
            user.setPic(uParam.getIdentityPic());
        }
        user.setHeight(uParam.getHeight());
        user.setWeight(uParam.getWeight());
        user.setIntroduction(uParam.getIntroduction());
        user.setWxId(uParam.getWxId());
        user.setNickName(uParam.getNickName());
        user.setUserMobile(uParam.getUserMobile());
        user.setLoginPassword(uParam.getPassword());
        user.setUserLabels(uParam.getUserLabels());
        user.setInvitatioCode(uParam.getInvitatioCode());
        user.setProvince(uParam.getProvince());
        user.setCity(uParam.getCity());
        user.setArea(uParam.getArea());
        user.setQrCode(uParam.getQrCode());
        user.setAge(uParam.getAge());
        user.setScore(0.0);
        user.setIsVip(0);
        user.setUserTitle(0);
        user.setIsOnline(0);
        user.setDiamondNum(0);
        user.setLikeMeCount(0);
        user.setTodayUnlockSurplus(0);


        return userMapper.insert(user) == 1;
    }

    @Override
    public Boolean insertForget(UserForget userForget){
        User user = userMapper.selectOne(new QueryWrapper<User>()
        .eq("user_mobile",userForget.getUserMobile()));
        if(user != null){
            user.setLoginPassword(userForget.getPassword());
        }else {
            return false;
        }
        return userMapper.updateById(user) == 1;
    }

    public List<User> getInvRecord(String userId){
        User user = userMapper.selectById(userId);
        List<User> InvRecord = userMapper.selectList(new QueryWrapper<User>().eq("upp_invitatio_code",user.getInvitatioCode()));
        return InvRecord;
    }

    @Override
    public void addDiamond(String userId, Integer amount) {
        Integer diamondNum = getById(userId).getDiamondNum();
        User user = new User();
        user.setUserId(userId);
        user.setDiamondNum(diamondNum + amount);
        updateById(user);
    }


    @Override
    public void addScoreByUid(String userId, double score, ProfitTypeConst profitType, String mark) {
        User one = getById(userId);
        Double oldScore = one.getScore();
        one.setScore(oldScore + score);
        updateById(one);

        //更新记录
        UserScoreRecord r = new UserScoreRecord();
        r.setUid(userId);
        r.setAmount(score);
        r.setType(2);
        r.setProfitType(profitType.getValue());
        r.setMark(mark);
        userScoreRecordService.addScoreRecord(r);
    }

    @Override
    public void subScoreByUid(String userId, double score, String mark) {
        User one = getById(userId);
        if (one == null) {
            throw new RuntimeException("无此用户");
        }
        double newScore;
        newScore = one.getScore() - score;
        if (newScore < 0) {
            throw new YamiShopBindException("积分不足");
        }
        one.setScore(newScore);
        updateById(one);

        //更新记录
        UserScoreRecord r = new UserScoreRecord();
        r.setUid(userId);
        r.setAmount(score);
        r.setType(1);
        r.setMark(mark);
        userScoreRecordService.addScoreRecord(r);
    }

    @Override
    public User getUserByUserMobile(String userMobile) {
        return getOne(Wrappers.lambdaQuery(new User())
                .eq(User::getUserMobile, userMobile));
    }

    @Override
    public List<UserCardDto> getRecommendUsers(User fromUser, Integer type) {
        List<User> f;
        if (fromUser.getSex().equals("M")) {
            f = list(Wrappers.lambdaQuery(new User())
                    .ne(User::getUserId, fromUser.getUserId()));
        } else {
            f = list(Wrappers.lambdaQuery(new User())
                    .ne(User::getUserId, fromUser.getUserId()));
        }

        return mapperFacade.mapAsList(f,UserCardDto.class);
    }

    /**
     * 根据距离排序
     */
    @Override
    public List<UserCardDto> getDisUser(Double lng,Double lat){
        List<UserCardDto> dtos = distanceMapper.queryDisUsers(lng,lat);
        return dtos;
    }

    /**
     * 根据距离排序(男性)
     */
    @Override
    public List<UserCardDto> getDisUserSex(Double lng,Double lat){
        List<UserCardDto> dtos = distanceMapper.queryDisUsersSex(lng,lat);
        return dtos;
    }

    /**
     * 根据新用户排序
     */
    @Override
    public List<UserCardDto> getNewUser(String uid,String sex){

        List<User> f;
        f = list(Wrappers.lambdaQuery(new User())
                .ne(User::getUserId,uid)
                .eq(sex.equals('M'),User::getSex,'F')//男性用户只显示女性
                .eq(User::getStatus,1)//状态正常
                .orderByDesc(User::getUserRegtime));

        return mapperFacade.mapAsList(f,UserCardDto.class);
    }

    /**
     * vip男生接口
     */
    @Override
    public List<UserCardDto> getVipMale(String uid){
        List<User> f;
        f = list(Wrappers.lambdaQuery(new User())
                .ne(User::getUserId,uid)
                .eq(User::getSex,'M')
                .eq(User::getStatus,1)//状态正常
                .eq(User::getIsVip,1));//vip

        return mapperFacade.mapAsList(f,UserCardDto.class);
    }

    /**
     * 根据是否在线排序
     */
    @Override
    public List<UserCardDto> getOnlUser(String uid,String sex){

        userMapper.editIsOnlx();

        List<User> f;
        f = list(Wrappers.lambdaQuery(new User())
                .ne(User::getUserId,uid)
                .eq(sex.equals('M'),User::getSex,'F')//男性用户只显示女性
                .eq(User::getStatus,1)//状态正常
                .orderByDesc(User::getIsOnline));

        return mapperFacade.mapAsList(f,UserCardDto.class);
    }

    /**
     * 按地区选择获取列表
     */
    @Override
    public List<UserCardDto> getLocUser(String uid,String prov,String city,String sex){
        List<User> f;
            f = list(Wrappers.lambdaQuery(new User())
                    .eq(sex.equals('M'),User::getSex,'F')//男性用户只显示女性
                    .eq(User::getProvince,prov)
                    .eq(User::getCity,city)
                    .eq(User::getStatus,1)//状态正常
                    .ne(User::getUserId,uid)
                    .orderByDesc(User::getIsOnline));
            return mapperFacade.mapAsList(f,UserCardDto.class);
    }

    /**
     * 判断邀请码性别接口
     */
    @Override
    public Integer judgeInv(String code){

        Integer count = userMapper.selectCount(new QueryWrapper<User>()
        .eq("invitatio_code",code));
        if(count == 0){
            return 3;//邀请码不存在
        }else if (count == 1){
            User user = userMapper.selectOne(new QueryWrapper<User>()
            .eq("invitatio_code",code));
            user.getSex();
            if (user.getSex().equals("M")){
                return 1;
            }else{
                return 2;
            }
        }
        return 4;
    }


    /**
     * 生成邀请码
     *
     * @return
     */
    public String createShareCode() {
        int maxNum = 10;
        int i;
        int count = 0;
        char[] str = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'};
        StringBuffer code = new StringBuffer("");
        Random r = new Random();
        while (count < 8) {
            i = Math.abs(r.nextInt(maxNum));
            if (i >= 0 && i < str.length) {
                code.append(str[i]);
                count++;
            }
        }


        return code.toString();
    }



}
